<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Userfarmaccount as UserfarmaccountMdl;
use app\admin\model\Farmaccounttype;
use app\admin\model\Image;

use think\Db;
use think\Exception;
use think\Request;

class Userfarmaccount extends BaseController
{

    /**
     * 首页
     */
    public function getHome()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->searchDate)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'searchDate 不能为空');
        }

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        //$searchDate = strtotime($param->searchDate);
        $startMonth = strtotime($param->searchDate . '-01');
        $endMonth = strtotime($param->searchDate . "-01 23:59:59 +1 month -1 day");
        $where = [
            'userId' => $userId,
            //'date' => [['egt', $searchDate], ['lt', $searchDate + 24*60*60*30], 'and']
            'date' => ['between time', [$startMonth, $endMonth]]
        ];

        $model = new UserfarmaccountMdl();
        $fields = '*';
        $order = 'date DESC';
        $result = $model->where($where)->field($fields)->limit(0, 100)->order($order)->select();
        $list = [];
        if($result){
            foreach ($result as $item) {
                $list[$item['date']][] = $item;
            }
            $list = array_values($list);
        }
        $total = $model->where($where)->count();
        // 月收入
        $monthAmountIn = $model->where($where)->where(['type' => 1])->sum('amount');
        // 月支出
        $monthAmountOut = $model->where($where)->where(['type' => 2])->sum('amount');

        // 小程序背景图
        $bgImage = 'https://' . $_SERVER['HTTP_HOST'] . '/public/static/wechat/image/userfarmaccount_bg.png';

        $data = [
            'bgImage' => $bgImage,
            'monthAmountIn' => $monthAmountIn ? : 0,
            'monthAmountOut' => $monthAmountOut ? : 0,
            'list' => $list ? : '',
            'total' => $total ? : 0,
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 统计
     */
    public function getStatistics()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->searchDate)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'searchDate 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        //$searchDate = strtotime($param->searchDate);
        $startMonth = strtotime($param->searchDate . '-01');
        $endMonth = strtotime($param->searchDate . "-01 23:59:59 +1 month -1 day");
        $where = [
            'userId' => $userId,
            'type' => $param->type
        ];
        $whereTime = [
            //'date' => [['egt', $searchDate], ['lt', $searchDate + 24*60*60], 'and']
            'date' => ['between time', [$startMonth, $endMonth]]
        ];

        $model = new UserfarmaccountMdl();
        $fields = '*';
        $order = 'date DESC';
        $list = $model->where($where)->where($whereTime)->group('categoryId')->field($fields)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->where($whereTime)->group('categoryId')->count();
        // 合计
        //$totalAmount = $model->where($where)->sum('amount');
        $totalAmount = $model->where($where)->where($whereTime)->sum('amount');

        if($list){
            //
        }

        $data = [
            'totalAmount' => $totalAmount ? : 0,
            'list' => $list ? : '',
            'total' => $total ? : 0,
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 保存
     */
    public function save()
    {
        $param = self::getHttpParam();

        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->categoryId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '分类(categoryId) 不能为空');
        }
        if (empty($param->amount)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '金额(amount) 不能为空');
        }
        if (empty($param->date)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '账单日期(date) 不能为空');
        }
        if (empty($param->remarks)) {
            //return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '备注(remarks) 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '类型(type) 不能为空');
        }

        $userId = $param->userId;

        Db::startTrans();
        try {
            $data = (array)$param;
            $data['date'] = strtotime($data['date']);

            $model = new UserfarmaccountMdl();

            if (!empty($param->id)) {
                $id = $param->id;
                $data['updateDate'] = time();
                $data['userId'] = $userId;

                $result = $model->allowField(true)->save($data, ['id' => $id]);
            } else {
                $data['id'] = BaseHelper::getUUID();
                $data['createDate'] = time();

                $result = $model->save($data);
            }

            if($result !== false){
                // 图片
                $res = '';
                if(isset($param->imgUrls) && $param->imgUrls) {
                    $imgUrls = (array) $param->imgUrls;
                    foreach($imgUrls as $key => $imgUrl){
                        $res = Image::where(['imgUrl' => $imgUrl])->update(['relatedId' => $data['id'], 'relatedTable' => 'userfarmaccount', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '保存图片失败');
                }
                Db::commit();
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '保存失败', $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '保存失败', $e->getMessage());
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new UserfarmaccountMdl();
        $field = '*';
        $item = $model->where($where)->field($field)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关数据');
        }

        // 图片
        $item['imgList'] = Image::where(['relatedId' => $item['id'], 'tag' => 'imglist'])->order('sorting ASC')->select();

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 删除
     */
    public function delete()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param->id
        ];
        $model = new UserfarmaccountMdl();
        $result = $model->where($where)->delete();
        if ($result === false) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败');
        }

        // Query执行后的操作
        $model->_after_delete($param->id);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }

    /**
     * 获取农事记账类型
     */
    public function getFarmaccounttypes(){
        $param = self::getHttpParam();

        /*if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }*/

        /*
        $where = [
            'type' => $param->type
        ];
        $model = new Farmaccounttype();
        $fields = 'id, name, imgUrl';
        $order = 'sorting ASC';
        $result = $model->where($where)->field($fields)->order($order)->select();
        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关数据');
        }
        */

        $result = [
            'outlay' => get_farmaccounttypes(1), // 支出
            'income' => get_farmaccounttypes(2), // 收入
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result);
    }
}